<?php


namespace app\home\model;


use think\Db;

class AttendanceDetail extends Base
{
    protected $insert = [
        'create_time' => NOW_TIME,
    ];

    /**
     * @param int $is_punch 是否考勤上报，1上报，0查看
     * @param int $is_exist 是否存在打卡记录，1存在，0不存在
     * @param $top_id 顶级科室id
     * @param $time 考勤时间
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPunchList($is_punch = 1,$is_exist = 0,$top_id,$time) {

        $department_1 = Db::table('zm_wechat_department')->where(['id' => $top_id])->find();
        if($department_1) {
            //获取顶级部门用户
            $map_1 = [ 'department' => $department_1['id'] ];
            $filed = ['userid,department as deparmentid,name as username'];
            $user_1 = Db::table('zm_wechat_user')->where($map_1)->field($filed)->select();
            if($user_1) {
                $department_1['user'] = $this->setUserStatus($is_punch,$is_exist,$top_id,$user_1,$department_1,$time);
            }
            //获取二级部门
            $department_main_2 = [];
            $department_2 = Db::table('zm_wechat_department')->where(['parentid' => $department_1['id']])->select();
            //如果是办公室部门，则添加领导考核
            if($department_2) {
                if($top_id == 5) {
                    $department_2_back = Db::table('zm_wechat_department')->where(['id' => 10])->select();
                    $department_2 = array_merge($department_2,$department_2_back);
                }
                foreach ($department_2 as $key => $value) {
                    $department_main_2[] = $value;
                    //获取三级部门
                    $department_3 = Db::table('zm_wechat_department')->where(['parentid' => $value['id']])->select();
                    if($department_3) {
                        foreach ($department_3 as $v) {
                            $department_main_2[] = $v;
                        }
                    }
                }
            }
            foreach ($department_main_2 as $key => $value) {
                $map_2 = [ 'department' => $value['id'] ];
                $user_2 = Db::table('zm_wechat_user')->where($map_2)->field($filed)->select();
                $department_main_2[$key]['user'] = $this->setUserStatus($is_punch,$is_exist,$top_id,$user_2,$value,$time);
            }
            $department = [
                'level_1' => $department_1,
                'level_2' => $department_main_2
            ];
            return $department;
        }else {
            return $this->error("无该用户对应科室部门");
        }
    }

    /**
     * @param $is_punch 是否考勤上报，1上报，0查看
     * @param $is_exist 是否存在打卡记录，1存在，0不存在
     * @param $top_id 顶级科室id
     * @param $user 用户数组
     * @param $department 部门数组
     * @param $time 打卡时间
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function setUserStatus($is_punch,$is_exist,$top_id,$user,$department,$time) {
        $start_time = strtotime(date("Y-m-d 00:00:00",$time));
        $end_time = strtotime(date("Y-m-d 23:59:59",$time));
        $query_time = $time + 24*60*60;
        foreach ($user as $key => $value) {
            $user[$key]['top_id'] = $top_id ;
            $user[$key]['parentid'] = $department['parentid'];
            $user[$key]['departmentname'] = $department['name'];
            //是否存在已打卡数据
            if($is_exist == 0) {
                //打卡还是查看状态
                if($is_punch == 1) {
                    $status = $this->checkLeaveMsg($value,$query_time);
                    if($status == 0) {
                        $user[$key]['status'] = $status;
                    }else {
                        $user[$key]['status'] = 1;
                    }
                }else {
                    if(time() >= $start_time && time() <= $end_time) {
                        $status = $this->checkLeaveMsg($value,$query_time);
                        if($status == 0) {
                            $user[$key]['status'] = $status;
                        }else {
                            $user[$key]['status'] = 1;
                        }
                    }else {
                        $user[$key]['status'] = 0;
                    }
                }
                $user[$key]['pid'] = "";
            }else {
                $map_user = [
                    'top_id' => $top_id,
                    'userid' => $value['userid'],
                    'attendance_time' => date("Y-m-d",$query_time)
                ];
                $res = $this->where($map_user)->find();
                if($res) {
                    //存在请假且有记录则更新改变状态
                    $status = $this->checkLeaveMsg($value,$query_time);
                    if($status == 0) {
                        if($res['status'] != 0) {
                            AttendanceDetail::where(['id' => $res['id']])->update(['status' => $status]);
                        }
                        $user[$key]['status'] = $status;
                    }else {
                        $user[$key]['status'] = $res['status'];
                    }
                    $user[$key]['pid'] = $res['pid'];
                }else {
                    $user[$key]['pid'] = "";
                    $user[$key]['status'] = 0;
                }
            }
        }
        return $user;
    }

    /**
     * 是否存在请假，改变状态
     * @param $value
     * @param $time
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkLeaveMsg($value,$time)
    {
//        $time = "1596470400";
        $query_time = date('Y-m-d',$time);
        $map = [
            'apply_user' => $value['userid'],
            'type' => 1,
            'status' => 1, //请假审批通过
            'FROM_UNIXTIME(start_time,"%Y-%m-%d")' => ['elt',$query_time],
            'FROM_UNIXTIME(end_time,"%Y-%m-%d")' => ['egt',$query_time]
        ];
        $res = ApprovalLeave::where($map)->find();
        if($res) {
            $status = 0; //请假
        }else {
            $status = -1; //未知
        }
        return $status;
    }


    /**
     * @param $top_id
     * @param $time
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getViewList($top_id,$time)
    {
        $department = $this->getViewDepartment($top_id);
        $list = $this->getViewUser($department,$time);
        return $list;
    }

    /**
     * 获取部门结构
     * @param $top_id 科室id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getViewDepartment($top_id) {
        $department = [];
        $department[] = Db::table('zm_wechat_department')->where(['id' => $top_id])->find();
        $department2 = Db::table('zm_wechat_department')->where(['parentid' => $top_id])->order('`order` desc')->select();
        if($department2) {
            foreach ($department2 as $key => $value) {
                $department[] = $value;
                $department3 = Db::table('zm_wechat_department')->where(['parentid' => $value['id']])->order('`order` desc')->select();
                if($department3) {
                    foreach ($department3 as $k => $v) {
                        $department[] = $v;
                    }
                }
            }
        }
        return $department;
    }

    /**
     * 获取用户列表及状态、统计值
     * @param $department
     * @param $time
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getViewUser($department,$time) {
        $count = [
            'total' => 0,
            'status_0' => 0,
            'status_1' => 0,
            'status_2' => 0
        ];
        foreach ($department as $key => $value) {
            $user = Db::table('zm_wechat_user')->where('department',$value['id'])->field('userid,name as username,0 as status')->select();
            foreach ($user as $k => $v) {
                $map = [
                    'userid' => $v['userid'],
                    'attendance_time' => date("Y-m-d",$time),
                ];
                $res = $this->where($map)->find();
                if($res) {
                    //存在请假且有记录则更新改变状态
                    $status = $this->checkLeaveMsg($v,$time);
                    if($status == 0) {
                        if($res['status'] != 0) {
                            AttendanceDetail::where(['id' => $res['id']])->update(['status' => $status]);
                        }
                        $user[$k]['status'] = $status;
                    }else {
                        $user[$k]['status'] = $res['status'];
                    }
                    if($user[$k]['status'] == 1) {
                        $count['status_1']++;
                    }else if($user[$k]['status'] == 2) {
                        $count['status_2']++;
                    }else {
                        $count['status_0']++;
                    }
                }
            }
            $count['total'] += $user_count = count($user);
            $department[$key]['user'] = $user;
        }
        $count['status_0'] = $count['total'] - ($count['status_1'] + $count['status_2']);
        $list = [
            'count' => $count,
            'department' => $department,
        ];
        return $list;
    }

}